# -*- coding: utf-8 -*-
import os
import settings

import pygame
from pygame.locals import *

class MovieSprite(pygame.sprite.Sprite):
    """
    Generic Movie Sprite which gets played when initiated
    """
    def __init__(self, scene, filename, mode):
        pygame.sprite.Sprite.__init__(self, scene.moviesprites)
        if pygame.mixer.get_init() is not None:
            pygame.mixer.quit()
        self.image = pygame.surface.Surface(settings.DIMENSIONS[mode]["size"])
        self.movie = pygame.movie.Movie(filename)
        self.size = self.movie.get_size()
        self.rect = self.image.get_rect()
        self.rect.top = settings.DIMENSIONS[mode]["top"]
        self.rect.left = settings.DIMENSIONS[mode]["left"]
        self.length = self.movie.get_length()
        self.duration = int(self.length*1000)
        self.movie.set_display(self.image)
    
    def update(self):
        """
        running on every cycle of the superior gameloop
        """
        if not self.movie.get_busy():
            self.movie.play()
            pygame.time.set_timer(settings.PLAYNEXT, self.duration-100)

class MoviePlayer(object):
    """
    abstract controller to manage movie opening, playing and stopping
    """
    def __init__(self, scene):
        self.index = 0
        self.scene = scene
        self.index_list = {}
        self.file_lists = {
            "preview": {},
            "full": {},
        }
        self.moviesprite = None
        self.last_played_filename = ""
        self.load_files()
    
    def load_files(self):
        """
        load movie files recursively from filesystem and devide between
        fullscreen and preview quality
        """
        for movdir, subdirs, files in os.walk(settings.MOVIE_PATH):
            for subdir in subdirs:
                for list_name in self.file_lists:
                    self.file_lists[list_name][subdir] = []
            for movie in files:
                file_path = os.path.join(movdir, movie)
                base_dir = os.path.basename(movdir)
                if movie.endswith(".mpg") and not movie.startswith("."):
                    if movie.startswith(settings.PREVIEW_PREFIX):
                        self.file_lists["preview"][base_dir].append(file_path)
                    # else:
                    #     self.file_lists["full"][base_dir].append(file_path)
    
    def clear(self, again=False):
        """
        let these damn movie sprites die in pain
        """
        if again:
            self.scene.moviesprites.empty()
            if self.moviesprite is not None:
                self.moviesprite = None
        else:
            if self.moviesprite is not None:
                self.moviesprite.kill()
    
    def play(self, mode, f_id, increment=None):
        """
        play movie with name like given f_id, fullscreen or preview
        """
        # decide which movie to play
        try:
            movie_type = settings.WORDS[f_id]
            self.movies_paths = self.file_lists[mode][movie_type]
            # delete movie sprite and references to memory (hopefully)
            try:
                self.clear()
            except:
                pass
            
            # try to load last index of the token
            if f_id in self.index_list:
                self.index = self.index_list[f_id]
            else:
                self.index = 0
            
            # increment movie index if needed
            if increment:
                self.index += increment
            
            # reset index if larger than movie list
            movie_count = len(self.movies_paths)
            if self.index >= movie_count:
                self.index = 0
            elif self.index < 0:
                self.index += movie_count
            
            # run clear again because pygames Movie objects die slowly
            try:
                self.clear(again=True)
            except:
                pass
            
            filename = self.movies_paths[self.index]
            if filename != self.last_played_filename:
                self.moviesprite = MovieSprite(self.scene, filename, mode)
                self.index_list[f_id] = self.index
                self.last_played_filename = filename
        except (KeyError, IndexError, pygame.error):
            pass
